<template>
  <div style="display: flex;">
    <!--    style="width: 80%"-->
    <!--    <Button @click="scrollEndFn">测试</Button>-->
    <div style="width: 80%" ref="contentRef">
      <div style="margin-top: 5px;margin-bottom: 5px;margin-left: 5px;font-weight: 700;display: flex">
        <div style="line-height: 30px;">库存:</div>
        <div style="margin-left: 10px">
          <vxe-button  status="primary" size="small" style="margin-left: 5px;" @click="initFn" content="搜索" ></vxe-button>

          <vxe-button status="warning"  size="small" style="margin-left: 15px;"  prefix-icon="vxe-icon-delete" @click="lightFn" content="亮灯" :loading="loading">
            <template #icon>
              <AlertOutlined />
            </template>
          </vxe-button>

        </div>
      </div>

      <!-- overflowY: 'auto', overflowX: 'hidden' -->
      <div :style="{ height: heightValue + 'px' }" class="m-table">
        <vxe-grid ref="tableRef" v-bind="gridOptions" v-on="gridEvents">
          <template #left_pager_slot>
            <div class="f-8">
              提示：剩余库存小于30%时，'库容预警'显示 <Tag color="#f5e509" class="f-8">黄色</Tag>；小于20%时显示 <Tag class="f-8"
                color="#f97124">橙色</Tag> ；小于10%时显示 <Tag class="f-8" color="#ff0021">红色</Tag>
            </div>

          </template>
          <template #header_mtid="{ column }">
            <div v-for="(option, index) in column.filters" :key="index">
              <Input v-model:value="filterObj.mtid" type="text" placeholder="查询物料编号" style="width: 100%;" @blur="blurFn"
                @keyup.enter="confirmFilterEvent(option, 'mtid')" size="small"></Input>
            </div>
          </template>
          <template #header_mname="{ column }">
            <div v-for="(option, index) in column.filters" :key="index">
              <Input v-model:value="filterObj.mname" type="text" placeholder="查询物料名称" style="width: 100%;"
                @focus="blurFn" @keyup.enter="confirmFilterEvent(option, 'mname')" size="small"></Input>
            </div>
          </template>
          <template #header_piCiHao="{ column }">
            <div v-for="(option, index) in column.filters" :key="index">
              <Input v-model:value="filterObj.piCiHao" type="text" placeholder="查询批次号" style="width: 100%;"
                @focus="blurFn" @keyup.enter="confirmFilterEvent(option, 'piCiHao')" size="small"></Input>
            </div>
          </template>
          <template #header_guige="{ column }">
            <div v-for="(option, index) in column.filters" :key="index">
              <Input v-model:value="filterObj.guige" type="text" placeholder="查询规格" style="width: 100%;" @focus="blurFn"
                @keyup.enter="confirmFilterEvent(option, 'guige')" size="small"></Input>
            </div>
          </template>
          <template #header_mmodel="{ column }">
            <div v-for="(option, index) in column.filters" :key="index">
              <Input v-model:value="filterObj.mmodel" type="text" placeholder="查询型号" style="width: 100%;"
                @focus="blurFn" @keyup.enter="confirmFilterEvent(option, 'mmodel')" size="small"></Input>
            </div>
          </template>
          <template #header_quantity_slot="{ }">
            <div>库存</div>
            <div>数量</div>
          </template>
          <template #header_residueNum_slot>
            <div>容量</div>
            <div>预警</div>
          </template>
          <template #kuWei_slot="{ row }">
            <div>
              <span>{{ row.kuWei }}</span>

              <div class="f-8" v-if="row.residueNum" :style="{ background: row.color, color: 'white' }">
                {{ row.residueNum }}

              </div>
              <!-- <Tag style="font-size: 0.8em;" :color="row.color" v-if="row.residueNum">
                <span class="f-8">
                </span>

              </Tag> -->
            </div>
          </template>
          <template #residueNum_slot="{ row }">
            <div>
              <!-- class="f-8"  -->
              <div v-if="row.color" :style="{ background: row.color, color: 'white' }">
                {{ row.residueNum }}
              </div>
              <div v-else>{{ row.residueNum }}</div>
            </div>
          </template>
        </vxe-grid>
      </div>
    </div>
    <!-- width: 18% -->
    <div style="width: 20%">
      <div :style="{ height: heightValue + 'px', overflowY: 'auto', overflowX: 'hidden' }">
        <div style="margin-top: 5px;margin-bottom: 5px;margin-left: 5px;font-weight: 700">库位:</div>
        <!-- gutter: 16, -->
        <div style="display: flex;font-size: 10px;">
          <div style="flex: 1">
            <List :grid="{ column: 1 }" :data-source="dataList">
              <template #renderItem="{ item }">
                <ListItem style="cursor: pointer;" @click="goFn(item)">
                  <div class="m-card" :style="item.kuWeiTid == selectId ? selectHeadStyle : {}">
                    <div v-if="item.title.length<6" style="text-align: center;">{{ item.title }}</div>
                    <div v-if="item.title.length>6" style="text-align: center;">
                      <div>{{ item.title.substring(0, 6) }}</div>
                      <div>{{ item.title.substring(6) }}</div>
                    </div>

                  </div>
                </ListItem>
              </template>
            </List>

          </div>
          <div style="flex: 1">
            <List :grid="{ column: 1 }" :data-source="dataList2">
              <template #renderItem="{ item }">
                <ListItem style="cursor: pointer;" @click="goFn(item)">
                  <div class="m-card" :style="item.kuWeiTid == selectId ? selectHeadStyle : {}">
                    <div v-if="item.title.length<6" style="text-align: center;">{{ item.title }}</div>
                    <div v-if="item.title.length>6" style="text-align: center;">
                      <div>{{ item.title.substring(0, 6) }}</div>
                      <div>{{ item.title.substring(6) }}</div>
                    </div>
                  </div>
                </ListItem>
              </template>
            </List>

          </div>
        </div>




      </div>

    </div>
    <StockListModal @register="stockModal[0]"></StockListModal>
  </div>
</template>
<script lang="ts" setup>
import {
  AlertOutlined
} from '@ant-design/icons-vue';
import { Card, List, ListItem, Tag, Input, Button } from 'ant-design-vue';
import { reactive, ref, onMounted } from 'vue';
import {dknWarehouseList, stockList, stockPcLight} from '@/api/heng/stock';
import { useRoute } from 'vue-router';
import { useUserStore } from '@/store/modules/user';
import util from '@/utils/util';
import StockListModal from './StockListModal.vue';
import { useModal } from "@/components/Modal";
import { columns, vxeTableFormSchema } from './role.data';
import {
  BasicTableProps,
  VxeTableDefines,
  VxeGridListeners,
} from '@/components/VxeTable';
import {useMessage} from "@/hooks/web/useMessage";
// import { useContentHeight } from '@/hooks/web/useContentHeight';

defineOptions({ name: 'dknWarehouse' });
const loading = ref(false);
const dataList = ref([]);
const dataList2 = ref([]);

const stockModal = useModal();
const contentRef = ref();
const route = useRoute();

const tableRef = ref();
const userStore = useUserStore();

const heightValue = ref(0);

const isJiaZi = ref(route.params?.isJiaZi);

const { createMessage } = useMessage();


const gridOptions = reactive<BasicTableProps>({
  // keepSource: true,
  // editConfig: { trigger: 'click', mode: 'cell', showStatus: true },
  border: true,
  showOverflow: true,
  size: 'mini',
  height: 'auto', // 'auto'
  columns: columns,
  filterConfig: {
    remote: true,
    showIcon: false
  },
  cellConfig: {
    height: 22
  },
  rowClassName: "f-8",
  headerRowClassName: "f-8",
  headerCellClassName: "f-8",
  toolbarConfig: {
    enabled: false,
    // slots: {
    //   buttons: 'toolbar_buttons',
    // },
    // refresh: true,
  },
  virtualYConfig: {
    // enabled: true,
    // immediate: true,
    gt: 5,

  },
  virtualXConfig: {
    enabled: false,
  },
  formConfig: {
    enabled: false,
    items: vxeTableFormSchema,
  },
  pagerConfig: {
    slots: {
      left: 'left_pager_slot',

    },
    // pagerCount:1,
    autoHidden:false,
    pageSize: 30,
    className: "f-8"
  },
  proxyConfig: {
    props: {
      result: 'data.list',
      list: 'data.list',
      total: 'data.totalResult',
      message: 'message',
    },
    filter: true,
    ajax: {
      query: (args, args2) => {
        // console.log("--args2:", args2);
        const { page, form, filters } = args;
        return findPageList(page, form, args2, filters);
      },
    },
  },
});


function initFn(data) {
  // selectValue.value = data;
  if (selectId.value) {
    if (selectId.value == data.kuWeiTid) {
      selectId.value = "";
    } else {
      selectId.value = data.kuWeiTid;
    }
  } else {
    selectId.value = data.kuWeiTid;
  }
  // gridOptions.proxyConfig.ajax.query(queryData);
  tableRef.value.commitProxy('reload');

}


function refresh() {
  setInterval(() => {
    userStore.refreshApi();
  }, 21600000);
  // 21600000    \6小时执行一次


}

// let queryData = {
//     page: {
//       currentPage: 1,
//       pageSize: 20,
//     }
//     , form: { kuWeiTid: data.kuWeiTid }
//   }

const filterObj = ref({
  mtid: "",
  mname: "",
  piCiHao: "",
  mmodel: "",
  guige: ""
})

const totalPage = ref(0);
const currentPage = ref(1);
const tableList = ref([]);
function findPageList(page, form, args2: any) {
  let json = {};

  for (let field in filterObj.value) {
    const value = filterObj.value[field];
    if (value) {
      json[field + 'Like'] = value;
    }
  }
  // console.log("---json:", json);

  let userParams = {
    kuWeiTid: selectId.value
  };


  return stockList({
    page: page.currentPage,
    pageSize: page.pageSize,
    isJiaZi: isJiaZi.value,
    ...form,
    ...userParams,
    ...json,
  }).then(res => {
    // setTimeoutScrollFn(res);
    totalPage.value = res.data.totalPage;
    tableList.value = res.data.list;
    return res;
  });
}

// const heightValue=computed(()=>contentRef.value?.offsetHeight);

onMounted(() => {

  loading.value = true;
  // window.innerHeight
  let dataJson = { isJiaZi: isJiaZi.value };
  // console.log("---dataJson:", dataJson);

  dknWarehouseList(
    {
      winameLikeBefore:"配件2区"
    }
    ).then(res => {
    loading.value = false;
    let arr= res.data.map(item => {
      return {
        kuWeiTid: item.oid,
        title: item.name,
        value: "",
        icon: "",
        color: "#004496",
      }
    });
    if(arr&&arr.length>0) {
      const middle = Math.ceil(arr.length / 2);
      let a1=arr.slice(0, middle);
      let a2=arr.slice(middle);
      dataList.value =a1;
      dataList2.value =a2;
    }
    // dataList.value = res.data.map(item => {
    //   return {
    //     kuWeiTid: item.oid,
    //     title: item.name,
    //     value: "",
    //     icon: "",
    //     color: "#004496",
    //   }
    // });
    // heightValue.value=contentRef.value?.offsetHeight;
    // initFn(null);
  });
  // dknWarehouseList({
  //   winameLikeBefore:"配件1区"
  // }).then(res => {
  //   loading.value = false;
  //   dataList2.value = res.data.map(item => {
  //     return {
  //       kuWeiTid: item.oid,
  //       title: item.name,
  //       value: "",
  //       icon: "",
  //       color: "#004496",
  //     }
  //   });
  //
  // });
  heightValue.value = window.innerHeight - 30;

  setTimeoutScrollFn();

  refresh();

})

var timeout = "";
let nextScroll = 0;

function setTimeoutScrollFn() {


  // timeout = setInterval(() => {
  //   if (tableRef.value) {
  //     let list = tableList.value;
  //     // console.log("--list:", list);
  //     if (list.length > 0) {
  //       // console.log("--nextScroll:", nextScroll);
  //       if (nextScroll < 13 * 22) {
  //         nextScroll += 1;
  //         tableRef.value.scrollTo(0, nextScroll);
  //
  //       } else {
  //         scrollEndFn();
  //         nextScroll = 0;
  //         tableRef.value.scrollTo(0, 0);
  //       }
  //     }
  //   }
  //
  //
  // }, 50);
}

function closeIntervalFn() {

  //clearInterval(timeout);
}

function scrollEndFn() {
  if (totalPage.value > currentPage.value) {
    currentPage.value = currentPage.value + 1;
  } else {
    currentPage.value = 1;
  }
  gridOptions.pagerConfig.currentPage = currentPage.value;
  tableRef.value.commitProxy('query');

}

function confirmFilterEvent(option, field) {

  // console.log("--field:", field);
  // filterObj[field] = option.data;
  // console.log("--filterObj:", filterObj.value);
  tableRef.value.commitProxy('reload');
  if (!filterObj.value[field]) {
    setTimeoutScrollFn();
  }
}




const gridEvents: VxeGridListeners<any> = {
  formReset({ data }) {
    // console.log("--formReset:", data);
    selectId.value = "";
    data.kuWeiTid = "";
    util.debounce(() => {
      tableRef.value.commitProxy('reload');

    }, 500);
  },


}

const selectValue = ref({});
const selectId = ref("");
// background: 'rgb(50 130 227)', color: 'white' color: 'rgb(50 130 227)',
const selectHeadStyle = ref({

  background: 'rgb(50 130 227)',
  color: 'white',
  borderRadius: '8px'
});

function fetchFn(e) {
  // console.log("---fetchFn:",e);
  // console.log("--contentRef.value?.offsetHeight:",contentRef.value?.offsetHeight)

  heightValue.value = contentRef.value?.offsetHeight;
}

function resetFn() {
  // console.log("--重置::");
  selectId.value = "";
  initFn(null);
}




function goFn(item) {
  // console.log(item);
  // stockModal[1].openModal(true, { ...item });
  //  console.log("--contentRef.value?.offsetHeight:",contentRef.value?.offsetHeight)
  initFn(item)
}


function keyupFn() {
  setTimeoutScrollFn()
}

function blurFn() {
  closeIntervalFn();
}

function lightFn(){
  let list = tableRef.value.getCheckboxRecords();

  if (list.length == 0) {
    createMessage.error('请勾数据!');
    return false;
  }
  loading.value = true;
  stockPcLight(list).then(res => {
    if(res.code == 200){
      createMessage.success(res.message);

    }else{
      createMessage.error(res.message);

    }
  }).finally(() => {
    loading.value = false;
  })
}


</script>

<style lang="less">
.item_w {
  width: 20%;
  word-wrap: break-word;
  word-break: normal;
}

.ant-list {
  .ant-list-item {
    padding: 4px;
  }
}

.ant-list-grid .ant-col>.ant-list-item {
  margin-block-end: 5px;

}


.m-card {
  max-width: 120px;
  margin: 1px;
  padding: 2px;
  border: 1px solid #d3cece;
  border-radius: 4px;
  font-size: 0.8em;
  cursor: pointer;
}

.m-table {
  // transform: scale(0.8);
  font-size: 0.7em;
}

.vue-devtools__anchor {
  display: none;
}

.headerCell {
  padding: 0;
}

.vxe-table--render-default.size--mini {
  .vxe-header--column.is--padding {
    .vxe-cell {
      padding: 0;
    }
  }
}

.vxe-grid--layout-body-content-wrapper {
  overflow: hidden;
}

.f-8 {
  font-size: 0.8em !important;
}
</style>
